/*
 * @Description:
 * @Autor: fage
 * @Date: 2022-07-26 17:49:48
 * @LastEditors: chenbinfa
 * @LastEditTime: 2022-08-16 17:06:54
 * @description: 描述信息
 * @author: chenbinfa
 */
import React, { useRef, useState, useEffect } from "react";
import {
	DatePicker,
	Input,
	InputNumber,
	Menu,
	Modal,
	Button,
	Tooltip,
	Dropdown,
	Descriptions,
	Select,
	Space,
	Table,
	message,
	Tabs,
	Popconfirm,
	Checkbox,
	Card,
	Form,
	Collapse,
	Empty,
	Spin,
	List
} from "antd";
import { LeftOutlined, DownOutlined, DeleteOutlined, SwapRightOutlined, CheckCircleOutlined, ExclamationCircleOutlined } from "@ant-design/icons";
import styled from "styled-components";
import _ from "lodash";
import { useNavigate, useParams, NavLink } from "react-router-dom";
import moment from "moment";
import copy from "copy-to-clipboard";
import { alertError, noti, notiError, notiOK } from "../../utils/antd-helper";
import * as suture from "../../services/suture";

import store from "../../utils/store";
import { checkLogin } from "../../services/user";

let lock = false;
let accountType = "";
let timeout = null;

function Main({ className }) {
	const { q } = useParams();
	const isNew = q === 'new';
	const isReactive = q.indexOf("reactive-") === 0;
	const isFrozen = q.indexOf("frozen-") === 0;
	let territoryName = isNew ? "" : q.slice(q.indexOf('-') + 1);
	const territoryInfo = window.modifyTerritory || {};
	// console.log({ territoryName, territoryInfo });
	let oldSpaceSize = territoryInfo.totalSpaceGib;

	const navigate = useNavigate();
	const [tab, setTab] = useState("space");
	const [inputName, setInputName] = useState("");
	const [inputGB, setInputGB] = useState(0);
	const [inputDay, setInputDay] = useState(30);
	const [account, setAccount] = useState({});
	const [needPayTotal, setNeedPayTotal] = useState(0);
	const [loading, setLoading] = useState(false);

	const init = async () => {
		let acc = store.get("account");
		setAccount(acc);
		if (isNew) {
			return;
		}
		if (!window.refreshSpace) {
			return setTimeout(init, 500);
		}
		acc = await window.refreshSpace();
	};
	useEffect(() => {
		let isLogin = checkLogin(navigate);
		if (isLogin) {
			init();
		}
	}, []);
	const tipError = (msg) => {
		clearTimeout(timeout);
		timeout = setTimeout(t => {
			notiError(msg);
		}, 600);
	}
	const onInputGB = e => {
		let v = e.target.value;
		if (isNaN(v)) {
			return tipError("Value only number");
		}
		if (v.indexOf('.') != -1) {
			return tipError("Value only integers");
		}
		if (v.length > 8) {
			return tipError("Value is out of range");
		}
		if (v && !isNaN(v)) {
			v = parseInt(v);
			setInputGB(v);
		}
		sumNeedPayTotal();
	};
	const onInputDay = e => {
		let v = e.target.value;
		if (isNaN(v)) {
			return tipError("Value only number");
		}
		if (v.indexOf('.') != -1) {
			return tipError("Value only integers");
		}
		if (v.length > 8) {
			return tipError("Value is out of range");
		}
		if (v && !isNaN(v)) {
			v = parseInt(v);
			setInputDay(v);
		}
		sumNeedPayTotal();
	};
	const onInputName = e => {
		let v = e.target.value;
		setInputName(v);
	};
	const valitBalance = () => {
		let coin = account.balance || 0;
		if (coin < needPayTotal) {
			throw new Error("Not enough balance.");
		}
	}
	const valitName = () => {
		if (!inputName) {
			throw new Error("The name is required.");
		}
		if (inputName.length > 63) {
			throw new Error("Territory name less than 63 characters.");
		}
		if (window.myTerritories.find(t => t.name == inputName)) {
			throw new Error("Duplicate territory name.");
		}
	}
	const valitInputGB = () => {
		if (!inputGB || inputGB < 1) {
			throw new Error("The space size is required.");
		}
	}
	const valitInputDay = (minDay) => {
		if (!inputDay || inputDay < 1) {
			throw new Error("The days is required.");
		}
		if (inputDay < minDay) {
			throw new Error("The days must more then " + minDay + ".");
		}
	}
	const onSubmit = async () => {
		try {
			if (lock) return;
			lock = true;
			setLoading(true);
			valitBalance();
			let ret = null;
			accountType = store.get("accountType");
			if (isNew) {
				valitInputGB();
				valitInputDay(30);
				valitName();
				ret = await suture.territoryCreat(inputName, inputGB, inputDay);
			} else if (isReactive) {
				valitInputDay(1);
				ret = await suture.territoryReactivate(territoryName, inputDay);
			} else if (isFrozen) {
				valitInputDay(1);
				ret = await suture.territoryExtendTime(territoryName, inputDay);
			} else if (tab == "space") {
				valitInputGB();
				ret = await suture.territoryExtendSize(territoryName, inputGB);
			} else {
				valitInputDay(1);
				ret = await suture.territoryExtendTime(territoryName, inputDay);
			}
			// let ret = await fun(input);
			console.log(ret);
			if (ret.msg == 'ok') {
				suture.territoryRefresh(true);
				navigate('/territories')
			}
		} catch (e) {
			console.log(e);
			alertError(e.message);
		} finally {
			lock = false;
			setLoading(false);
		}
	};
	const onTabChange = t => {
		setTab(t);
		setNeedPayTotal(0);
	};
	const sumNeedPayTotal = () => {
		let t = 0;
		if (isNew) {
			t = inputDay * inputGB;
		} else if (isReactive) {
			t = inputDay * oldSpaceSize;
		} else if (isFrozen) {
			t = inputDay * oldSpaceSize;
		} else if (tab == 'space') {
			t = inputGB * territoryInfo.remainingDays;
		} else {
			t = inputDay * oldSpaceSize;
		}
		setNeedPayTotal(t);
	}

	return (
		<div className={className}>
			<Spin spinning={loading}>
				<div className="t1">{isNew ? "Purchase a new territory" : isReactive ? "Reactive Territory" : "Upgrade the territory"}</div>
				<div className="t11">
					<span onClick={() => navigate('/territories')}>My territories</span>
					{!isNew && <label onClick={() => navigate('/territory/new')}>Buy territory</label>}
				</div>
				<div className="con">
					{!isNew && !isReactive && !isFrozen && (
						<div className="tab">
							<span
								className={tab == "space" ? "curr" : ""}
								onClick={() => {
									onTabChange("space");
								}}>
								Extend Space
							</span>
							<span
								className={tab == "time" ? "curr" : ""}
								onClick={() => {
									onTabChange("time");
								}}>
								Extend Time
							</span>
						</div>
					)}
					{
						isNew ? (
							<>
								<div className="t2">Space</div>
								<input onInput={onInputGB} onKeyUp={onInputGB} onChange={onInputGB} className="input1" type="number" placeholder="GB" />
								<div className="t2-1">Estimated 1 CESS / GB</div>
								<div className="t4">Avaliable Time</div>
								<input onInput={onInputDay} onKeyUp={onInputDay} onChange={onInputDay} placeholder="At least 30 days" className="input1" type="number" />
								<div className="t2">Territory Name</div>
								<input onInput={onInputName} onKeyUp={onInputName} onChange={onInputName} className="input1" type="text" placeholder="Less than 63 characters" />
							</>) :
							isReactive ? (
								<>
									<div className="t4">Time</div>
									<input onInput={onInputDay} onKeyUp={onInputDay} onChange={onInputDay} placeholder="Day" className="input1" type="number" />
									<div className="t2-1">Estimated 1 CESS / GB / per day</div>
									<div className="t2">Purchased Space</div>
									<input value={oldSpaceSize + "GB"} className="input1" readOnly={true} />
								</>) :
								isFrozen ? (
									<>
										<div className="t2">Extend Time</div>
										<input onInput={onInputDay} onKeyUp={onInputDay} onChange={onInputDay} className="input1" type="number" placeholder="Day" />
										<div className="t2-1">Estimated 1 CESS / GB / per day</div>
										<div className="t2">Purchased Space</div>
										<input value={oldSpaceSize + "GB"} className="input1" readOnly={true} />
										<div className="t4">Avaliable Time</div>
										<input className="input1" type="text" value={territoryInfo.remainingDays + " Days"} readOnly={true} />
									</>) :
									tab == "space" ? (
										<>
											<div className="t2">Extend Space</div>
											<input onInput={onInputGB} onKeyUp={onInputGB} onChange={onInputGB} className="input1" type="number" placeholder="GB" />
											<div className="t2-1">Estimated 1 CESS / GB / per day</div>
											<div className="t2">Purchased Space</div>
											<input value={oldSpaceSize + "GB"} className="input1" readOnly={true} />
											<div className="t4">Avaliable Time</div>
											<input className="input1" type="text" value={territoryInfo.remainingDays + " Days"} readOnly={true} />
										</>) : (
										<>
											<div className="t2">Extend Time</div>
											<input onInput={onInputDay} onKeyUp={onInputDay} onChange={onInputDay} className="input1" type="number" placeholder="Day" />
											<div className="t2-1">Estimated 1 CESS / GB / per day</div>
											<div className="t2">Purchased Space</div>
											<input value={oldSpaceSize + "GB"} className="input1" readOnly={true} />
											<div className="t4">Avaliable Time</div>
											<input className="input1" type="text" value={territoryInfo.remainingDays + " Days"} readOnly={true} />
										</>)
					}
					<div className="block">
						<span>Total</span>
						<span>{needPayTotal} CESS</span>
						<label>Available: {account.balance_str}</label>
					</div>
					<div className="btn1" onClick={onSubmit}>
						Confirm & Signature
					</div>
				</div>
			</Spin>
		</div>
	);
}

export default styled(Main)`
	width: 100%;
	.t1 {
		color: rgb(51, 51, 51);
		line-height: 37px;
		margin: 60px 0 16px;
		font-size: 36px;
		font-weight: bold;
		text-align: center;
	}
	.t11{
		display: flex;
		flex-direction: row;
		width: 98%;
		max-width: 640px;
		height: 80px;
		margin:0 auto;
		border-bottom: 1px solid #dddddd;
		align-items: center;
		justify-content: space-between;
		span{
			display: flex;
			flex-direction: row;
			align-items: center;
			gap:10px;
			cursor: pointer;
			&:hover{
				color:#555;
			}
			&::before{
				content:"";
				background-image: url("/img/back.svg");
				background-repeat: no-repeat;
				background-position: center;
				background-size: 30px;
				width:30px;
				height:30px;
				display: block;
				overflow: hidden;
			}
		}
		label{
			width: 140px;
			height: 50px;
			line-height: 50px;
			border-radius: 5px;
			border: 1px solid #c3c3c3;
			background-color: rgba(51, 51, 51, 0);
			color: #000000;
			text-align: center;
			font-size: 16px;
			cursor: pointer;
			&:hover{
				background-color: #ddd;
			}
		}		
	}
	.con {
		width: 520px;
		border-radius: 30px;
		overflow: hidden;
		padding: 0 50px 50px;
		display: flex;
		flex-direction: column;
		align-items: center;
		font-size: 14px;
		margin: 0 auto;
		.tab {
			width: 262px;
			height: 46px;
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			margin: 20px auto;
			span {
				width: 49%;
				line-height: 46px;
				border: 1px solid #fff;
				border-radius: 6px;
				color: #aaa;
				text-align: center;
				font-size: 16px;
				cursor: pointer;
			}
			.curr {
				border: 1px solid #000;
				color: #000;
			}
		}		
		.t2,
		.t4 {
			font-size: 20px;
			font-weight: bold;
			color: rgb(51, 51, 51);
			line-height: 74px;
		}
		.t2-1 {
			font-size: 14px;
			margin-bottom: 20px;
		}
		.t3 {
			width: 85%;
			border-radius: 48px;
			height: 48px;
			line-height: 48px;
			border: 1px solid rgb(195, 195, 195);
			background-repeat: no-repeat;
			background-position: 35px center;
			background-size: 30px;
			text-align: center;
			color: rgb(59, 59, 59);
			cursor: pointer;
		}
		.t3:hover {
			background-color: #f5f5f5;
		}
		.input1 {
			width: 85%;
			border-radius: 48px;
			height: 48px;
			line-height: 48px;
			border: 1px solid rgb(195, 195, 195);
			text-align: center;
			outline: none;
			background-color: transparent;
		}
		.block {
			background-color: rgba(240, 240, 240, 1);
			border-radius: 15px;
			width: 434px;
			color: #3b3b3b;
			display: flex;
			flex-direction: column;
			line-height: 30px;
			text-align: center;
			margin-top: 40px;
			padding: 10px 0;
			label {
				color: #737373;
			}
		}
		.btn1 {
			border-radius: 48px;
			height: 48px;
			line-height: 48px;
			width: 50%;
			text-align: center;
			background-color: #000;
			color: #fff;
			margin-top: 48px;
			cursor: pointer;
		}
		.btn1:hover {
			background-color: rgb(49 48 48);
		}
		.t5 {
			display: flex;
			flex-direction: row;
			width: 178px;
			height: 50px;
			line-height: 50px;
			justify-content: space-between;
			align-items: center;
			margin-top: 130px;
			color: rgb(59, 59, 59);
			font-weight: bold;
		}
	}
`;
